// Copyright 2007 Helsinki Institute for Information Technology
// and the authors.
//
// Authors: Petri Savolainen <petri.savolainen@hiit.fi>
//          Harri Hämäläinen <harri.hamalainen@helsinki.fi>

// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

function Util () {}

Util.get_params = function() 
    {
    var result = {};

    var q = location.search;
    if (q.length > 1) {
        q = q.substring(1, q.length);

        var fields = q.split('&');
        for (var i = 0; i < fields.length; i += 1) {
            var parts = fields[i].split('=');
            var key = parts[0];
            var value = parts[1];
            result[key] = decodeURIComponent(value);
        }
    }

    return result;
    }

Util.getDefaultProfile = function() 
    {
    var info = HttpConnector.doGet('/info?output=json'); 
    info = eval('(' + info + ')'); 
    return info.default_profile;
    }

Util.getFingerprint = function() 
    {
    return HttpConnector.doGet('/collection/'+Util.getDefaultProfile()+'?output=sha1-hex');
    }
    
Util.getRealName = function()
    {
    var data = HttpConnector.doGet('/info?output=json');
    var obj = data.evalJSON(true);
    var defaultProfile = obj['default_profile'];
    return HttpConnector.doGet('/collection/'+defaultProfile+'/info/title');
    }

Util.formatDate = function(date)
	{
	var ret = '';
	ret += date.getFullYear()+'-';
    	var month = (date.getMonth()+1);
	ret += Util.pad(month)+'-'+Util.pad(date.getDate());
	return ret;
	}

Util.getISODate = function()
    {
    var date = new Date();
    var ret = '';

    ret += date.getFullYear()+'-';
    var month = (date.getMonth()+1);


    ret += Util.pad(month)+'-'+Util.pad(date.getDate())+'T';
    ret += Util.pad(date.getHours())+':'+ Util.pad(date.getMinutes()) +':';
    ret += Util.pad(date.getSeconds())+'.';

    var smillis = ''+date.getMilliseconds();
    while (smillis.length<3)
        smillis = '0' + smillis;
    smillis+='000';

    ret += smillis;

    return ret;
    }

Util.getUTCDate = function()
    {
    var localDate = new Date();
    var date = new Date(localDate.valueOf() +
        localDate.getTimezoneOffset()*1000*60);

    var ret = '';
    
    ret += date.getFullYear()+'-';
    var month = (date.getMonth()+1);
    
    ret += Util.pad(month)+'-'+Util.pad(date.getDate())+'T';
    ret += Util.pad(date.getHours())+':'+ Util.pad(date.getMinutes()) +':';
    ret += Util.pad(date.getSeconds());
    ret += 'Z'
    return ret;
    }

Util.getUTCFriendlyDate = function(inputDate) 
    {
    var localDate = new Date();
    var uniDate = Util.parseUTCDate(inputDate);
    localDate = new Date(uniDate.valueOf() -
        localDate.getTimezoneOffset()*1000*60);
    var ret = '';
    ret += localDate.getFullYear()+'-';
    var month = (localDate.getMonth()+1);
    ret += Util.pad(month)+'-'+Util.pad(localDate.getDate())+'T';
    ret += Util.pad(localDate.getHours())+':'
        + Util.pad(localDate.getMinutes()) +':';
    ret += Util.pad(localDate.getSeconds());
    return Util.getFriendlyDate(ret);
    }

Util.getFriendlyDate = function(inputDate)
    {
    var date = inputDate.match(/(\d+-\d+-\d+)/)[1];
    date += " " + inputDate.match(/(\d+:\d+:\d+)/)[1];
    return date;
    }

Util.isSameDate = function(date1, date2)
	{
	if (date1.getDate() == date2.getDate() && date1.getMonth() == date2.getMonth() && date1.getFullYear() == date2.getFullYear())	
		return true;
	return false;	
	}

Util.parseUTCDate = function(utcdate) 
    {
    var year = parseInt(utcdate.substring(0,4), 10);		
	var month = parseInt(utcdate.substring(5,7), 10);	
	var day = parseInt(utcdate.substring(8,10), 10);
	var hour = parseInt(utcdate.substring(11,13), 10);
	var minute = parseInt(utcdate.substring(14,16), 10);
	var second =  parseInt(utcdate.substring(17,19), 10);	
	var date = new Date();	
	
	date.setFullYear(year);	
	date.setMonth(month-1);
	date.setDate(day);	
	date.setHours(hour);

	date.setMinutes(minute);		
	date.setSeconds(second);

	return date;
	}

Util.parseDate = function(isodate)
	{	
	var year = parseInt(isodate.substring(0,4), 10);		
	var month = parseInt(isodate.substring(5,7), 10);	
	var day = parseInt(isodate.substring(8,10), 10);
	
	var hour = parseInt(isodate.substring(11,13), 10);
	var minute = parseInt(isodate.substring(14,16), 10);
	var second =  parseInt(isodate.substring(17,19), 10);	
	var millisecond = parseInt(isodate.substring(20,23), 10); 

	var date = new Date();	
	
	date.setFullYear(year);	
	date.setMonth(month-1);
	date.setDate(day);	
	date.setHours(hour);

	date.setMinutes(minute);		
	date.setSeconds(second);
	date.setMilliseconds(millisecond);

	return date;
	}


Util.pad = function(s)
    {
    var ret = ''+s;
    if (ret.length<2)
        ret='0'+ret;
    return ret;
    }

Util.escape = function(text)
    {
    if (text instanceof Array) {
        for (var i=0; i<text.length; i += 1) {
            text[i] = Util.escape(text[i]);
        }
    }
    else {
        text = text.replace(/</g,'&lt;');
        text = text.replace(/>/g,'&gt;');
    }
    return text;
    }

Util.randomHex = function(size) {
  var ret = "0x"
  for (var i=0; i<size; i+=1) {
    var hex = (Math.random()*16 | 0);
    ret += hex.toString(16);
  }
  return ret;
}

Util.getRightedGroups = function(right) {
    var result = eval('(' + HttpConnector.doGet('../rights/?output=json') + ')');
    var data = result.data;
    var groups = [];
    for (var i = 0; i < data.length; i += 1) {
        var k = data[i][0];
        var v = data[i][1];
        if (v == '1') {
            var slash = k.indexOf('/');
            var group = k.substring(2, slash);
            if (k.substring(slash) == right) {
                groups.push(group);
            }
        }
    }
    return groups;
}

Util.disableRights = function(right) {
    var result = eval('(' + HttpConnector.doGet('../rights/?output=json') + ')');
    var data = result.data;

    for (var i = 0; i < data.length; i += 1) {
        var k = data[i][0];
        var v = data[i][1];
        if (v == '1') {
            var slash = k.indexOf('/');
            var group = k.substring(2, slash); // Skip leading "0x".
            if (k.substr(slash) == right) {
                HttpConnector.doPut('../rights/'+k, '0');
            }
        }
    }
}

Util.enableRights = function(right, group, role) {
    if (!group) {
        var info = eval('(' + HttpConnector.doGet('/info?output=json') + ')');
        group = info.default_profile;
    }

    if (!role) {
        role = 'friend';
    }

    var url = '../rights/0x' + group + '/' + role + right;
    HttpConnector.doPut(url, '1');
}
